import { SERVERS_INFO, PATHS_INFO } from './api.js'

export const http = ({ path, params, header, success, fail, complete }) => {
  // 接口名、参数、content-type,成功回调、失败回调、统一回调
  // let authtoken = wx.getStorageSync('authToken')
  let pathInfo = PATHS_INFO[path];
  let url = SERVERS_INFO[pathInfo.server].host + pathInfo.path;
  if (params && params.urlParams) {   //重置接口地址
    url = url + params.urlParams;
    delete params.urlParams;
  }

  let headerDefault = {
    // authtoken: authtoken,
    // "content-type": "application/x-www-form-urlencoded",
    "content-type": "application/json",
    'appId': "com.smk.test.test"
  }

  wx.request({
    url: url,
    data: params == null ? {} : params,
    method: pathInfo.method,
    header: header == null ? headerDefault : header,
    success: function ({ data }) {
      if (data.code === 0 || data.code === 'PY0000') {
        if (success != null) success(data)
      } else if (data.code === 'PY0005'){   //第三方登录--手机号码不正确
        if (fail != null) fail(data)
      } else if ( typeof data == 'string'&&data.indexOf('404 Not Found')>-1){    //404 not Fond
        wx.showToast({
          title: '服务器出错',
          icon:'none'
        })
      }else {
        // console.log(`请求失败${url},code=>${data.code},params=>${JSON.stringify(params)}`);
        wx.hideLoading();
        wx.showToast({
          title: data.msg,
          icon: 'none',
          duration:2000
        });
        // wx.showToast({
        //   title: data.message || (data.code && data.message),
        //   icon: 'none'
        // });
        if (fail != null) fail(data)
      }
    },
    fail: function (e) {
      // console.log(e);
      wx.hideLoading();
      wx.showToast({
        title: '网络异常，请重试',
        icon: 'none'
      });
      //console.log(`请求失败${url}, error=>${JSON.stringify(e)}`);
      if (fail != null) fail(e)
    },
    complete: function (data)
    {
      // console.log(data.data, `path=>${pathInfo.path},params=>${JSON.stringify(params)}`);
      if (complete != null) complete()
    }
  })
}

export default {
  http,
}